package com.example.sunmiv1.activity;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.sunmiv1.R;
import com.example.sunmiv1.adapter.VipListAdapter;
import com.example.sunmiv1.entity.MemberListBean;
import com.example.sunmiv1.utils.ByteArrayTohexHepler;
import com.example.sunmiv1.utils.net.ACache;
import com.example.sunmiv1.utils.net.Common;
import com.example.sunmiv1.utils.net.GsonUtils;
import com.example.sunmiv1.utils.net.HttpUtils;
import com.example.sunmiv1.utils.net.LoadingDialog;
import com.example.sunmiv1.utils.net.TextCallBack;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshGridView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.example.sunmiv1.utils.ByteArrayTohexHepler.ByteArrayToHexString;
import static com.example.sunmiv1.utils.ByteArrayTohexHepler.flipHexStr;

public class VipListActivity extends Activity {

    @BindView(R.id.title_back)
    ImageView titleBack;
    @BindView(R.id.title_title)
    TextView titleTitle;
    @BindView(R.id.vipList_gridView)
    PullToRefreshGridView vipListGridView;
    @BindView(R.id.vipList_search_edit)
    EditText vipListSearchEdit;
    @BindView(R.id.vipList_search_iv)
    ImageView vipListSearchIv;

    private Context context;
    private ACache aCache;
    private LoadingDialog loadingDialog;
    private List<MemberListBean.ViplistBean> list;
    private VipListAdapter vipListAdapter;
    private Intent intent;
    private String type;
    private int page = 1;
    private static final String TAG = "vipListActivity";
    private MemberListBean memberlistBean;

    //nfc
    private NfcAdapter mNfcAdapter;
    private PendingIntent pi;
    private boolean isSupportNfc, isOpenNfc;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    loadingDialog.dismiss();
                    vipListGridView.onRefreshComplete();
                    Toast.makeText(context, memberlistBean.getMsg(), Toast.LENGTH_SHORT).show();
                    page++;
                    for (int i = 0; i < memberlistBean.getViplist().size(); i++) {
                        list.add(memberlistBean.getViplist().get(i));
                    }
                    setVipListAdapter();
                    break;
                case 2:
                    loadingDialog.dismiss();
                    vipListGridView.onRefreshComplete();
                    Toast.makeText(context, memberlistBean.getMsg(), Toast.LENGTH_SHORT).show();
                    setVipListAdapter();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_vip_list);
        context = this;
        aCache = ACache.get(context);
        loadingDialog = new LoadingDialog(context);
        ButterKnife.bind(this);
        titleTitle.setText(R.string.vipListTitle);
        type = getIntent().getStringExtra("type");
        initData();
        //nfc
        PackageManager packageManager = this.getPackageManager();
        isSupportNfc = packageManager.hasSystemFeature(PackageManager.FEATURE_NFC);
        Log.e(TAG, "onCreate: isSupportNfc=" + isSupportNfc);
        if (isSupportNfc) {
            mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
            pi = PendingIntent.getActivity(this, 0, new Intent(this, getClass())
                    .addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
            if (mNfcAdapter != null && !mNfcAdapter.isEnabled()) {
                isOpenNfc = false;
            } else {
                isOpenNfc = true;
            }
        }
    }

    private void initData() {
        list = new ArrayList<>();
        vipListGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                intent = new Intent(context, VipDetailsActivity.class);
                intent.putExtra("vid", list.get(position).getId());
                startActivity(intent);
            }
        });
        vipListGridView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<GridView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<GridView> refreshView) {
                vipListSearchEdit.setText("");
//                page = 1;
//                list.clear();
//                getvipList();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<GridView> refreshView) {
                getvipList();
            }
        });
        vipListSearchEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if(s.toString().trim().length()==0){
                    page = 1;
                    list.clear();
                    getvipList();
                }
            }
        });
        vipListSearchEdit.setImeOptions(EditorInfo.IME_ACTION_SEND);
        vipListSearchEdit.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                //當actionId == XX_SEND 或者 XX_DONE時都觸發
                //或者event.getKeyCode == ENTER 且 event.getAction == ACTION_DOWN時也觸發
                //注意，這是一定要判斷event != null。因爲在某些輸入法上會返回null。
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                // 強制隱藏軟鍵盤
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                if ((event != null && KeyEvent.KEYCODE_ENTER == event.getKeyCode() && KeyEvent.ACTION_DOWN == event.getAction())) {
                    if ("".equals(vipListSearchEdit.getText().toString())) {
                            Toast.makeText(context, "請輸入要搜索的內容", Toast.LENGTH_SHORT).show();
                    } else {
                        page = 1;
                        list.clear();
                        getvipList();
                    }
                }
                return false;
            }
        });
        getvipList();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mNfcAdapter != null && isSupportNfc && isOpenNfc) {
            mNfcAdapter.enableForegroundDispatch(this, pi, null, null);
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        // Toast.makeText(context, "onNewIntent", Toast.LENGTH_SHORT).show();
        /*Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        //獲取 Tag 讀取 ID 得到字節數組  轉字符串 轉碼  得到卡號（默認16進制 這請自便）
        String num1 = ByteArrayToHexString(tag.getId());
        if (num1.length() > 10) {
            vipListSearchEdit.setText(num1);
            return;
        }
        String num2 = flipHexStr(num1);
        Log.e(TAG, "onNewIntent: 1=" + num2);
        String num = "";
        if (num2.length() > 10) {
            try {
                num = ByteArrayTohexHepler.hex2String(num2);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            Long cardNo = Long.parseLong(num2, 16);
            Log.e(TAG, "onNewIntent: 2=" + cardNo);
            num = cardNo.toString();
        }
        if (num.length() != 10) {
            while (num.length() < 10) {
                num = "0" + num;
            }
        }*/
        String ex_id;
        Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        String num1 = ByteArrayToHexString(tagFromIntent.getId());
        String num2 = flipHexStr(num1);
        Log.e(TAG, "onNewIntent: 1=" + num2);
        String num = "";
        if (num2.length() > 10) {
            try {
                num = ByteArrayTohexHepler.hex2String(num2);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            Long cardNo = Long.parseLong(num2, 16);
            Log.e(TAG, "onNewIntent: 2=" + cardNo);
            num = cardNo.toString();
        }
        if (num.length() != 10) {
            while (num.length() < 10) {
                num = "0" + num;
            }
        }
        ex_id = num;
        //Toast.makeText(getApplicationContext(), num, Toast.LENGTH_SHORT).show();
        vipListSearchEdit.setText(ex_id);
        vipListSearchEdit.setSelection(ex_id.length());
        page = 1;
        list.clear();
        getvipList();
    }

    private void setVipListAdapter() {
        if (vipListAdapter == null) {
            vipListAdapter = new VipListAdapter(context, list);
            vipListGridView.setAdapter(vipListAdapter);
        } else {
            vipListAdapter.notifyDataSetChanged();
        }
    }

    private void getvipList() {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("type", type);
            jsonObject.put("page", page);
            jsonObject.put("keyword",vipListSearchEdit.getText().toString());
            jsonObject.put("storeid", aCache.getAsString("storeid"));
            jsonObject.put("merchantid", aCache.getAsString("merchantid"));
            HttpUtils.post(context, Common.GET_VIP_LIST, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    memberlistBean = GsonUtils.JsonToBean(text, MemberListBean.class);
                    Message msg = new Message();
                    if (memberlistBean.getStatus() == 1) {
                        msg.what = 1;
                    } else {
                        msg.what = 2;
                    }
                    handler.sendMessage(msg);
                }

                @Override
                protected void onFailure(ResponseException e) {
                    loadingDialog.dismiss();
                    vipListGridView.onRefreshComplete();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @OnClick({R.id.title_back,R.id.vipList_search_iv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                finish();
                break;
            case R.id.vipList_search_iv:
                if(TextUtils.isEmpty(vipListSearchEdit.getText().toString().trim())){
                    Toast.makeText(context, "請輸入要搜索的內容", Toast.LENGTH_SHORT).show();
                    return;
                }
                page = 1;
                list.clear();
                getvipList();
                break;
        }
    }
}
